package com.example.demo.config;

import javax.sql.DataSource;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.equity", sqlSessionTemplateRef = "sqlSessionTemplateSecondary")
public class SecondaryConfig {
	private DataSource secondaryDataSource;

	public SecondaryConfig(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
		this.secondaryDataSource = secondaryDataSource;
	}

	@Bean
	public SqlSessionFactory sqlSessionFactorySecondary() throws Exception {
		MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		mybatisSqlSessionFactoryBean.setDataSource(secondaryDataSource);
		mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/equity/*.xml"));
//		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//		bean.setDataSource(secondaryDataSource);
		MybatisConfiguration configuration = new MybatisConfiguration();
		configuration.setMapUnderscoreToCamelCase(true);
		configuration.setCacheEnabled(false);
		configuration.setLogImpl(StdOutImpl.class);
		mybatisSqlSessionFactoryBean.setConfiguration(configuration);
		return mybatisSqlSessionFactoryBean.getObject();
	}

	/**
	 * 配置事务管理器，不然事务不起作用
	 * 
	 * @return
	 */
	@Bean
	public PlatformTransactionManager transactionManagerSecondary() {
		return new DataSourceTransactionManager(secondaryDataSource);
	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplateSecondary() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactorySecondary());
	}
}